﻿using BoldBrick.Core.Logging;
using BoldBrick.OneIntranet.HR.DataObjects;
using BoldBrick.OneIntranet.HR.DataObjects.ContentTypes;
using BoldBrick.OneIntranet.HR.DataObjects.Lists;
using Microsoft.SharePoint;
using BoldBrick.SharePoint.CommonControls.Extensions;

namespace BoldBrick.OneIntranet.HR.EventHandlers
{
	public class WorkflowsListItemAdded : SPItemEventReceiver
	{
		private static readonly ILogger log = Logger.GetLogger(typeof(WorkflowsListItemAdded));

		public override void ItemAdded(SPItemEventProperties properties)
		{
			base.ItemAdded(properties);

			SPListItem listItem = properties.ListItem;
			log.Write(LogLevel.Info, "ItemAdded for '{0}' item started.", listItem.Url);

			SPFolder folder = listItem.Folder;
			
			// if item is folder, set onctent types
			if (folder == null)
			{
				string orderFieldName = SiteColumns.WorkflowStepOrderColumn.InternalName;
				int? order = listItem.GetValue<int>(orderFieldName);
				bool updated = false;
				if (!order.HasValue)
				{
					order = listItem.ID*100;
					log.Write(LogLevel.Info, "Set order = {0} for list item with '{1}' list item.", order, listItem.Url);
					listItem[orderFieldName] = order;
					updated = true;
				}
				if (string.IsNullOrEmpty(listItem.Title))
				{
					listItem[SharePoint.CommonControls.DataObjects.SiteColumns.TitleColumn.InternalName] =
						listItem[SharePoint.CommonControls.DataObjects.SiteColumns.ContentTypeColumn.InternalName];
					updated = true;
				}

				if (updated)
				{
					listItem.Update(false);
				}
			}
			else
			{
				SPSecurity.RunWithElevatedPrivileges(delegate
				{
					using (SPSite site = new SPSite(properties.SiteId))
					{
						using (SPWeb web = site.OpenWeb(properties.Web.ID))
						{
							SPList list = web.Lists[properties.ListId];
							SPListItem item = list.GetItemById(properties.ListItemId);
							folder = item.Folder;
							
							Lists.WorkflowsList.SetupContentTypeUniqueOrder(list, folder);
						}
					}
					
				});

				
			}
		}

	}
}
